package bat.iog.hytool.reactor.single;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * 单Reactor单线程模型
 */
public class Reactor implements Runnable {

    private ServerSocketChannel serverSocketChannel = null;

    private Selector selector = null;
    
    //绑定端口注册监听事件
    public Reactor() {
        try {
            //创建多路复用器selector
            selector = Selector.open();
            //创建ServerSocketChannel
            serverSocketChannel = ServerSocketChannel.open();
            //切换为非阻塞模式
            serverSocketChannel.configureBlocking(false);
            //绑定端口
            serverSocketChannel.socket().bind(new InetSocketAddress(8888));
            //将通道注册到选择器上, 并且指定“监听接收事件”
            //调用 SocketChannel 的注册方法将 SocketChannel 注册到 Selector 上，注册方法返回一个 SelectionKey，该 SelectionKey 
            //会被放入 Selector 内部的 SelectionKey 集合中。该 SelectionKey 和 Selector 关联（即通过 SelectionKey 
            //可以找到对应的 Selector），也和 SocketChannel 关联（即通过 SelectionKey 可以找到对应的 SocketChannel）。
            SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            //将给定的对象附加到此键。
            selectionKey.attach(new Acceptor());
            System.out.println("服务器启动正常!");
        } catch (IOException e) {
            System.out.println("启动服务器时出现异常!");
            e.printStackTrace();
        }
    }

    public void run() {
        while (true) {
            try {
                //selector.select()会一直阻塞到有一个通道在你注册的事件上就绪了
                selector.select();
                
                //找到所有准备就绪的key
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
              
                System.out.println("接收网络请求！");
                while (iter.hasNext()) {
                    SelectionKey selectionKey = iter.next();
                    //1.获取当前的附加对象。进行分发处理，开启一个线程处理接收连接处理
                    //2.处理读操作
                    dispatch((Runnable) selectionKey.attachment());
                    iter.remove();
                }
                
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //进行分发任务
    public void dispatch(Runnable runnable) {
        if (runnable != null) {
            runnable.run();
        }
    }

    public static void main(String[] args) {
        new Thread(new Reactor()).start();
    }

    class Acceptor implements Runnable {
        public void run() {
            try {
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel != null) {
                    System.out.println("接收到来自客户端（" + socketChannel.socket().getInetAddress().getHostAddress() + "）的连接");
                    new Handler(selector, socketChannel);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 连接过后通过Handler处理数据
 */
class Handler implements Runnable {

    private static final int READ_STATUS = 1;

    private static final int WRITE_STATUS = 2;

    private final SocketChannel socketChannel;

    private SelectionKey selectionKey;

    private int status = READ_STATUS;

    public Handler(Selector selector, SocketChannel socketChannel) {
        //获取管道传输数据
        this.socketChannel = socketChannel;
        try {
            //配置为非阻塞
            socketChannel.configureBlocking(false);
            //将通道注册到选择器上, 并且指定事件
            selectionKey = socketChannel.register(selector, 0);
            //将此键的兴趣集设置为给定值。可以随时调用此方法。 它是否阻塞以及阻塞多长时间取决于实现。
            selectionKey.interestOps(SelectionKey.OP_READ);
            //将给定的对象附加到此键。
            selectionKey.attach(this);
            selector.wakeup();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            if (status == READ_STATUS) {
                read();
                selectionKey.interestOps(SelectionKey.OP_WRITE);
                status = WRITE_STATUS;
            } else if (status == WRITE_STATUS) {
                process();
                selectionKey.cancel();
                System.out.println("服务器发送消息成功!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void read() throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        socketChannel.read(buffer);
        System.out.println("接收到来自客户端（" + socketChannel.socket().getInetAddress().getHostAddress() + "）的消息：" + new String(buffer.array()));
    }

    public void process() throws IOException {
        String content = "Hello World!";
        ByteBuffer buffer = ByteBuffer.wrap(content.getBytes());
        socketChannel.write(buffer);
    }
}
